<template>
	<view>
		<up-navbar title="添加工作经历" @leftClick="leftClick" safeAreaInsetTop placeholder>
		</up-navbar>
		<up-form labelWidth="80" labelPosition="left" :model="model1" :rules="rules"
			ref="form1">
			<up-divider></up-divider>
			<up-form-item prop="workExpencience.companyName" borderBottom ref="item1">
				<template #label>
					<up-row>
						<up-col span="4">
							<up-text text="公司名称" align="center" size="20px"
								@blur="validateField('workExpencience.companyName')"></up-text>
						</up-col>
						<up-col offset="1" span="7">
							<up-input placeholder="请输入公司名" font-size="20px" v-model="model1.workExpencience.companyName"
								border="none"></up-input>
							<up-text v-if="errors.companyName" color="red" :bold="true" text="请输入公司名称"></up-text>
						</up-col>
					</up-row>
				</template>
			</up-form-item>
			<up-divider></up-divider>
			<up-form-item @click="toChoosePosition()" prop="workExpencience.position" borderBottom ref="item1">
				<template #label>
					<up-row>
						<up-col span="4">
							<up-text text="行业/职位" align="center" size="20px"></up-text>
						</up-col>
						<up-col span="7" offset="1">
							<up-input @click="workShow = true" font-size="20px"
								v-model="model1.workExpencience.occupationName" disabled disabledColor="#ffffff"
								placeholder="请选择职位" border="none"></up-input>
							<up-text v-if="errors.position" color="red" :bold="true" text="请选择职位"></up-text>
						</up-col>
					</up-row>
				</template>
				<template #right>
					<up-icon name="arrow-right" style="margin-right: 35px;"></up-icon>
				</template>
			</up-form-item>
			<up-divider></up-divider>
			<up-row>
				<up-col span="3">
					<up-text text="在职时间" align="center" size="20px"></up-text>
				</up-col>
				<up-col span="3" offset="1">
					<up-form-item prop="workExpencience.joinDate" borderBottom ref="item1">
						<up-text :text="model1.workExpencience.joinDate" size="20px" :color="startColor"
							@click="startShow=true"></up-text>
					</up-form-item>
					<up-text v-if="errors.joinDate" color="red" :bold="true" text="请选择时间"></up-text>
				</up-col>
				<up-col span="1">
					——
				</up-col>
				<up-col span="3" offset="0.5">
					<up-form-item prop="workExpencience.leaveDate" borderBottom ref="item1">
						<up-text :text="model1.workExpencience.leaveDate" size="20px" :color="endColor"
							@click="endShow=true"></up-text>
					</up-form-item>
					<up-text v-if="errors.leaveDate" color="red" :bold="true" text="请选择时间"></up-text>
				</up-col>
			</up-row>
			<up-datetime-picker :show="startShow" v-model="startValue" mode="year-month" @confirm="startTimeConfirm"
				@cancel="startShow=false" @close="startShow=false" :closeOnClickOverlay="true"></up-datetime-picker>
			<up-datetime-picker :show="endShow" v-model="endVaule" mode="year-month" @confirm="endTimeConfirm"
				@cancel="endShow=false" @close="endShow=false" :closeOnClickOverlay="true"></up-datetime-picker>
			<!-- <up-divider></up-divider> -->
			<up-form-item prop="workExpencience.content" borderBottom ref="item1">
				<up-cell-group>
					<up-cell :border="false">
						<template #title>
							<up-text text="工作内容" size="20px" style="margin-left: -5px;"></up-text>
						</template>
					</up-cell>
					<up-cell @click="editJobContent">
						<template #title>
							<up-text :text="model1.workExpencience.jobContent" lines="2" size="20px"
								:color="jobContentColor"></up-text>
							<up-text v-if="errors.jobContent" color="red" :bold="true" text="请输入工作内容"></up-text>
						</template>
						<template #right-icon>
							<up-icon name="arrow-right" style="margin-right: 20px;"></up-icon>
						</template>
					</up-cell>
				</up-cell-group>
			</up-form-item>
		</up-form>
		<view class="save">
			<up-button type="error" v-if="model1.workExpencience.experienceId != ''"
				style="margin-right: 10px;width: 200px;" size="large" text="删除" @click="delShow = true"></up-button>
			<up-button type="primary" size="large" text="保存" @click="submitForm()"></up-button>
		</view>
		<up-modal :content="content" :show="show" showCancelButton closeOnClickOverlay @confirm="confirm"
			@cancel="cancel" @close="show = false" contentTextAlign="center"></up-modal>
		<up-modal :content="delContent" :show="delShow" showCancelButton closeOnClickOverlay @confirm="delForm()"
			@cancel="delCancel" @close="delShow = false" contentTextAlign="center"></up-modal>
	</view>
</template>

<script>
	export default {
		onShow() {
			//获取行业选择传回的对象
			if (uni.getStorageSync('item') !== '') {
				const data = uni.getStorageSync('item');
				this.model1.workExpencience.occupationName = data.name2;
				this.model1.workExpencience.industry = data.name1;
				uni.removeStorageSync('item');
			}
			//获取工作内容传回的对象
			uni.getStorage({
				key: 'jobContent',
				success: (res) => {
					console.log('获取的数据：', res.data);
					this.workContent = res.data;
				},
				fail: (err) => {
					// console.error('获取数据失败：', err);
					this.workContent = err.data;
				},
			});
			// const jobContent = uni.getStorage('jobContent');  
			console.log('jobContent:', this.workContent); // 输出实际内容   
			if (this.workContent !== null && this.workContent !== undefined) {
				if (uni.getStorageSync('jobContent') !== '') {
					const data = uni.getStorageSync('jobContent');
					if (data !== 'cancel') {
						this.model1.workExpencience.jobContent = data;
						this.jobContentColor = 'black';
						uni.removeStorageSync('jobContent');
					} else {
						uni.removeStorageSync('jobContent');
					}
				} else {
					this.model1.workExpencience.jobContent = '请输入内容';
					this.jobContentColor = '#c4c9cf'
				}
			}
		},
		onLoad(options) {
			
			//获取上一个页面传回的对象
			if (options.value != null) {
				// console.log(JSON.parse(options.value).companyName)
				// console.log(options.value)
				this.model1.workExpencience = JSON.parse(options.value);
				this.submitJoinDate = this.convertToTimestamp(this.model1.workExpencience.joinDate);
				this.submitLeaveDate = this.convertToTimestamp(this.model1.workExpencience.leaveDate);
				this.startColor = 'black';
				this.endColor = 'black;'
				this.jobContentColor = 'black'
			}
		},
		data() {
			return {
				model1: {
					workExpencience: {
						experienceId: '',
						resumeId: 1,
						companyName: '',
						industry: '',
						occupationName: '',
						joinDate: '入职时间',
						leaveDate: '至今',
						jobContent: '请输入内容',
						remarks: '',
					}
				},
				errors: {
					companyName: '',
					occupationName: '',
					joinDate: '',
					leaveDate: '',
					jobContent: '',
				},
				//行业
				workShow: false,
				// 入职时间
				startShow: false,
				startValue: Number(new Date()),
				startColor: '#c4c9cf',
				//入职时间提交
				submitJoinDate: '',
				// 离职时间
				endShow: false,
				endVaule: Number(new Date()),
				endColor: '#c4c9cf',
				//离职时间提交
				submitLeaveDate: '',
				//工作内容颜色
				jobContentColor: '#c4c9cf',
				workContent: '',
				//提示退出
				content: '是否要保存再返回',
				show: false,
				//删除
				delContent: '确定要删除该经历？',
				delShow: false,
			}
		},
		methods: {
			validateField(field) {
				switch (field) {
					case 'companyName':
						this.errors.companyName = this.model1.workExpencience.companyName ? '' : '请输入公司名称';
						break;
					case 'occupationName':
						this.errors.occupationName = this.model1.workExpencience.occupationName ? '' : '请选择职位';
						break;
					case 'joinDate':
						this.errors.joinDate = this.model1.workExpencience.joinDate === '入职时间' ? '请选择入职时间' : '';
						break;
					case 'leaveDate':
						this.errors.leaveDate = this.model1.workExpencience.leaveDate === '至今' ? '请选择离职时间' : '';
						break;
					case 'jobContent':
						this.errors.jobContent = this.model1.workExpencience.jobContent === '请输入内容' ? '请输入工作内容' : '';
						break;
				}
			},
			//导航栏返回
			leftClick() {
				this.show = true;
			},
			//前往选择行业和职位
			toChoosePosition() {
				uni.navigateTo({
					url: '/pages/positions/positions'
				})
			},
			//起始时间确认
			startTimeConfirm(startDate) {
				if (!startDate.value || isNaN(startDate.value)) {
					console.error('无效的日期值:', startDate.value);
					return; // 终止执行  
				}
				this.submitJoinDate = startDate.value;
				// 将时间戳转换为 Date 对象
				const date = new Date(startDate.value);
				// 获取年份和月份  
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以需要加 1，并且补零  
				// 格式化为 "年 - 月" 的形式  
				const formattedDate = `${year}-${month}`;
				this.model1.workExpencience.joinDate = formattedDate;
				this.startColor = 'black';
				this.startShow = false;

			},
			//结束时间确认
			endTimeConfirm(endDate) {
				console.log('endDate.value:', endDate.value);
				// 检查 endDate.value 是否有效  
				if (!endDate.value || isNaN(endDate.value)) {
					console.error('无效的日期值:', endDate.value);
					return; // 终止执行  
				}
				this.submitLeaveDate = endDate.value;
				// 将时间戳转换为 Date 对象  
				const date = new Date(endDate.value);
				// 获取年份和月份  
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以需要加 1，并且补零  
				// 格式化为 "年 - 月" 的形式  
				const formattedDate = `${year}-${month}`;
				//存值
				this.model1.workExpencience.leaveDate = formattedDate;
				//调色
				this.endColor = 'black';
				//关闭选择器
				this.endShow = false;
			},
			//将年-月转换为时间戳
			convertToTimestamp(yearMonth) {
				// 将字符串转换为日期对象  
				const [year, month] = yearMonth.split('-');
				// 创建一个新的 Date 对象，设置为该月的第一天  
				const date = new Date(year, month - 1); // month - 1 因为月份是从 0 开始的  
				// 获取时间戳（以毫秒为单位）  
				return date.getTime(); // 返回时间戳  
			},
			//将时间戳转换为dateTime形式
			changeToDateTime(timestamp) {
				const date = new Date(timestamp);

				// 获取年、月、日、时、分、秒  
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以加1  
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');
				const seconds = String(date.getSeconds()).padStart(2, '0');

				// 格式化为 ISO 8601 格式  
				const dateTimeString = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.000Z`;
				return dateTimeString;
			},
			//打开入职时间选择器
			openStartTime() {
				console.log("")
				this.startShow = true;
			},
			//前往工作内容编辑页面
			editJobContent() {
				uni.navigateTo({
					url: '/pages/personal/jobContentView?jobContentByWorkE=' + this.model1.workExpencience
						.jobContent
				})
			},
			//切换页面时给字体重新赋颜色
			getColor(workExp) {
				if (workExp.jobContent !== '请输入内容') {
					this.jobContentColor = 'black'
				} else {
					this.model1.workExpencience.jobContent = '请输入内容'
					this.jobContentColor = '#c4c9cf'
				}
				if (workExp.joinDate !== '入职时间') {
					this.startColor = 'black';
				}
				if (workExp.leaveDate !== '至今') {
					this.endColor = 'black';
				}
			},
			//删除取消
			delCancel() {
				uni.navigateTo({
					url: "/pages/personal/onlineResumeView"
				})
			},
			//删除该经历
			delForm() {
				// 调用数据库删除
				this.$api.delUserWorkExp({
					experienceId: this.model1.workExpencience.experienceId
				}).then((res) => {
					if (res.data === 'ok') {
						uni.showToast({
							title: '删除成功',
							icon: 'success',
							complete() {
								uni.navigateTo({
									url: "/pages/personal/onlineResumeView"
								})
							}
						})
					} else {
						uni.showToast({
							title: '删除失败',
							icon: 'fail',
						})
					}
				})
			},
			//返回不保存
			cancel() {
				uni.navigateTo({
					url: "/pages/personal/onlineResumeView"
				})
			},
			//返回保存
			confirm() {
				this.submitForm()
			},
			//保存
			submitForm() {
				// 手动验证每个字段
				this.validateField('companyName');
				this.validateField('occupationName');
				this.validateField('joinDate');
				this.validateField('leaveDate');
				this.validateField('jobContent');

				// 检查是否有错误
				let hasError = false;
				for (let key in this.errors) {
					if (this.errors[key]) {
						hasError = true;
						break;
					}
				}
				// 检查时间是否正确
				if (this.model1.workExpencience.joinDate > this.model1.workExpencience.leaveDate) {
					uni.showToast({
						title: '入职时间必须小于离职时间',
						icon: 'none'
					});
					return;
				}
				// 检查入职时间是否大于当前时间
				if (new Date(this.model1.workExpencience.joinDate) > new Date()) {
					uni.showToast({
						title: '入职时间不能大于当前时间',
						icon: 'none'
					});
					return;
				}
				if (hasError) {
					this.show = false;
					return;
				}
				console.log(this.submitLeaveDate);
				// 保存数据
				if (this.model1.workExpencience.experienceId != '') {
					//修改数据
					this.$api.updateUserWorkExp({
							experienceId: this.model1.workExpencience.experienceId,
							resumeId: this.model1.workExpencience.resumeId,
							companyName: this.model1.workExpencience.companyName,
							industry: this.model1.workExpencience.industry,
							occupationName: this.model1.workExpencience.occupationName,
							joinDate: this.changeToDateTime(this.submitJoinDate),
							leaveDate: this.changeToDateTime(this.submitLeaveDate),
							jobContent: this.model1.workExpencience.jobContent,
						})
						.then((res) => {
							uni.showToast({
								title: `${res.code === 200 ? '修改成功' : '修改失败'}`,
								icon: 'none'
							});
							uni.navigateTo({
								url: "/pages/personal/onlineResumeView"
							});
						})
				} else {
					//添加数据
					this.$api.addUserWorkExp({
						resumeId: this.model1.workExpencience.resumeId,
						companyName: this.model1.workExpencience.companyName,
						industry: this.model1.workExpencience.industry,
						occupationName: this.model1.workExpencience.occupationName,
						joinDate: this.changeToDateTime(this.submitJoinDate),
						leaveDate: this.changeToDateTime(this.submitLeaveDate),
						jobContent: this.model1.workExpencience.jobContent,
					}).then((res) => {
						console.log(res)
						uni.showToast({
							title: `${res.code === 200 ? '保存成功' : '保存失败'}`,
							icon: 'none'
						});
						uni.navigateTo({
							url: "/pages/personal/onlineResumeView"
						});
					});
				}
			}
		}
	}
</script>

<style>
	.save {
		position: fixed;
		bottom: 0;
		width: 95%;
		background-color: #fff;
		padding: 10px;
		box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
		display: flex;
	}

	.custom-error {
		color: blue;
		/* 修改错误提示颜色 */
		font-weight: bold;
		/* 加粗 */
		margin-top: 5px;
		/* 提示和输入框之间的间距 */
	}
</style>